package gr.gsis.cobol;

public class PictureUtils {

	public static String expand(String picture) {
		StringBuilder sb = new StringBuilder();
		
		int pos = 0;
		char lastChar = 0;
		while (pos < picture.length()) {
			char c = picture.charAt(pos);

			if (c == '(') {
				int repeatStartPos = pos + 1;
				int repeatEndPos = repeatStartPos;
				while (picture.charAt(repeatEndPos) != ')') {
					repeatEndPos++;
					
					if (repeatEndPos > picture.length()) {
						throw new IllegalArgumentException(
								"No endpoint parenthesis found for repeat factor starting at pos: " + 
								repeatStartPos);
					}
				}
				
				int repeat = Integer.parseInt(picture.substring(repeatStartPos, repeatEndPos));
				
				// By design the first character will have always been printed,
				// so subtract one from repeat factor
				repeat--;
				
				for (int i=0; i< repeat; i++) {
					sb.append(lastChar);
				}
				
				pos = repeatEndPos + 1;
				continue;
			}
		
			sb.append(c);
			lastChar = c;
			
			pos++;
		}
		
		return sb.toString();
	}
	
	public static int getLength(String picture) {
		int decimalPoints = 0;
		int pos = 0;
		
		while (pos <= picture.length()) {
			if (picture.indexOf('V', pos) != -1) {
				decimalPoints++;
				pos = picture.indexOf('V') + 1;
			} else {
				pos = picture.length() + 1;
			}
		}
		
		return picture.length() - decimalPoints;
	}
	
}
